<template>
  <el-card class="add-container" shadow="hover">
    <el-row :gutter="20">
      <!-- 左侧表单区域 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" class="form-section">
        <div class="section-header">
          <el-icon class="icon">
            <Collection />
          </el-icon>
          <h3>{{ $t('message.random.collectionDetails') }}</h3>
          <el-button type="primary" @click="loadCollects" icon="Box" class="action-button">{{
            $t('message.router.PromptPanel')
            }}</el-button>

          <el-button type="success" @click="addCollect" icon="Plus" class="action-button">{{ $t('message.common.add')
            }}</el-button>
        </div>

        <el-form ref="collectForm" :model="collect" label-position="top" class="custom-form">
          <el-form-item :label="$t('message.random.selectClassType')" prop="class_type">
            <el-select v-model="collect.class_type" :placeholder="$t('message.random.selectClassType')"
              class="form-input">
              <el-option v-for="item in state.classType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('message.random.keyName')" prop="name">
            <el-input v-model="collect.name" type="text" :placeholder="$t('message.random.keyName')" class="form-input">
              <template #prefix>
                <el-icon>
                  <Key />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item :label="$t('message.random.customizeName')" prop="customize_name">
            <el-input v-model="collect.customize_name" type="text" :placeholder="$t('message.random.customizeName')"
              class="form-input">
              <template #prefix>
                <el-icon>
                  <EditPen />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item :label="$t('message.random.tags')" prop="tags">
            <el-input v-model="collect.tags" type="textarea" resize="none"
              :placeholder="$t('message.random.tagsPlaceholder')" :autosize="{ minRows: 3, maxRows: 5 }"
              class="form-input">
              <template #prefix>
                <el-icon>
                  <PriceTag />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item :label="$t('message.random.ratingFavorite')">
            <div class="rating-favorite-container">
              <div class="rating-item">
                <el-text class="mr5">{{ $t('message.random.favorite') }}:</el-text>
                <el-switch v-model="collect.favorite" inline-prompt :active-text="$t('message.common.yes')"
                  :inactive-text="$t('message.common.no')" active-color="#13ce66" />
              </div>
              <div class="rating-item">
                <el-text class="mr5">{{ $t('message.random.rating') }}:</el-text>
                <el-rate v-model="collect.rating" show-score :max="10" allow-half clearable
                  score-template="{value} points" class="custom-rate" />
              </div>
            </div>
          </el-form-item>
        </el-form>
      </el-col>

      <!-- 右侧图片区域 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" class="image-section">
        <el-tabs v-model="activateName">
          <el-tab-pane :label="$t('message.random.imagePreview')" name="image">
            <div class="image-preview-container">
              <div class="preview-card" :class="{ 'no-image': !collect.image }">
                <el-image v-if="collect.image" :src="collect.image" fit="cover" hide-on-click-modal
                  :preview-src-list="[collect.image]" class="preview-image">
                  <template #toolbar="{ actions, activeIndex }">
                    <div class="custom-viewer-toolbar">
                      <el-tooltip effect="dark" :content="$t('message.random.resetZoom')" placement="top">
                        <el-button size="default" @click="actions.reset" circle>
                          <el-icon>
                            <ZoomOut />
                          </el-icon>
                        </el-button>
                      </el-tooltip>

                      <el-tooltip effect="dark" :content="$t('message.random.download')" placement="top">
                        <el-button size="default" @click="generationStore.handleDownload(collect.image)" circle>
                          <el-icon>
                            <Download />
                          </el-icon>
                        </el-button>
                      </el-tooltip>

                      <el-tooltip effect="dark" :content="$t('message.random.previous')" placement="top">
                        <el-button size="default" @click="actions.prev" circle>
                          <el-icon>
                            <ArrowLeft />
                          </el-icon>
                        </el-button>
                      </el-tooltip>

                      <el-tooltip effect="dark" :content="$t('message.random.next')" placement="top">
                        <el-button size="default" @click="actions.next" circle>
                          <el-icon>
                            <ArrowRight />
                          </el-icon>
                        </el-button>
                      </el-tooltip>
                    </div>
                  </template>
                </el-image>

                <div v-else class="image-placeholder">
                  <el-icon class="placeholder-icon">
                    <PictureRounded />
                  </el-icon>
                  <p>{{ $t('message.random.noImage') }}</p>
                </div>
              </div>

              <el-upload 
                ref="imageUpload"
                action="#" 
                accept=".jpg,.jpeg,.png,.webp" 
                :auto-upload="false" 
                :show-file-list="false" 
                drag
                :on-change="handleCollectFileChange" 
                class="image-uploader"
              >
                <el-icon class="upload-icon">
                  <UploadFilled />
                </el-icon>
                <div class="el-upload__text">
                  {{ $t('message.random.uploadImage') }}<br>
                  <span class="el-upload__tip">{{ $t('message.random.uploadImageTip') }}</span>
                </div>
              </el-upload>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="$t('message.random.metadata')" name="metadata">
            <div class="metadata-section">
              <el-input v-model="metadata.data" type="textarea" resize="none" :placeholder="$t('message.random.raw')"
                :autosize="{ minRows: 7, maxRows: 10 }" class="metadata-input"></el-input>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="$t('message.home.setting')" name="setting">
            <NodeFieldMapEditor
              v-model="userNodeFieldMap"
              @submit="handleConfigSubmit"
            />
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup lang="ts" name="AddPrompt">
import { ElMessage, FormInstance} from 'element-plus'
import { reactive, ref, defineAsyncComponent } from 'vue'
import { useGenerationStore } from '@renderer/stores/useGenerationStore'
import { useConfigStore } from '@renderer/stores/configStore'
import { commonApi } from '@renderer/api/common'
import { join } from 'path-browserify'
import { ipcService } from '@renderer/services/ipcService'

// 定义NodeFieldMap类型
interface NodeFieldMap {
  [key: string]: string;
}

// 异步导入NodeFieldMapEditor组件
const NodeFieldMapEditor = defineAsyncComponent(() => 
  import('@renderer/views/random/component/NodeFieldMapEditor.vue')
);

const currentUploadFile = ref<File | null>(null)
const imageUpload = ref(null)

const configStore = useConfigStore()
const generationStore = useGenerationStore()
const collect = reactive({
  name: '',
  customize_name: '',
  class_type: 'collect',
  image: '',
  tags: '',
  description: '',
  rating: 0.0,
  favorite: false,
  disliked: false
})
const activateName = ref("image")
const metadata = reactive({
  data: '',
})
// 用户节点字段映射配置
const userNodeFieldMap = ref<NodeFieldMap>({});

const state = reactive({
  classType: [
    { label: '收藏', value: 'collect' },
    { label: '风格', value: 'style' },
    { label: '动作', value: 'action' },
    { label: '服装', value: 'cloth' },
    { label: '预设', value: 'preset' },
    { label: '反向', value: 'negative' }
  ]
})
const collectForm = ref<FormInstance | null>(null)
const emit = defineEmits(['loadCollects'])

const addCollect = async () => {
  try {
    // 表单验证
    if (!collectForm.value) return

    await collectForm.value.validate()
    
    // 1. 先插入数据库获取主键ID
    const response = await commonApi().addPromptItem({
      ...collect,
      image: '' // 初始化为空
    });

    if (!response.data?.success || !response.data.result?.id) {
      throw new Error('获取记录ID失败')
    }

    const id = response.data.result.id;
    ElMessage.success(`记录创建成功，ID: ${id}`);

    // 2. 如果有图片，使用ID作为文件名保存
    if (currentUploadFile.value) {
      try {
        // 构建保存路径
        const savePath = join(
          configStore.config.imagesPath, 
          'collections', 
          `${id}.webp`
        )
        
        // 调用IPC方法保存图片，传递File对象和路径
        const saveResult = await ipcService.saveWebpImage(
          currentUploadFile.value, 
          savePath
        )
        
        if (saveResult.success) {
          // 更新数据库记录，设置图片路径
          await commonApi().updatePromptItem({
            id: id, 
            image: savePath 
          });
          ElMessage.success('图片保存成功');
        } else {
          ElMessage.warning(`图片保存失败: ${saveResult.error || '未知错误'}`);
        }
      } catch (error) {
        ElMessage.error(`图片保存失败: ${error instanceof Error ? error.message : '未知错误'}`);
      } finally {
        // 无论成功失败都清空文件
        clearUploadFile()
      }
    }

    // 3. 重置表单
    resetForm()
    
    // 4. 通知父组件刷新列表
    emit('loadCollects')

  } catch (error) {
    ElMessage.error(`操作失败: ${error instanceof Error ? error.message : '未知错误'}`);
  } finally {
  }
}

const handleCollectFileChange = async (uploadFile: any) => {
  try {
    // 验证文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp']
    if (!validTypes.includes(uploadFile.raw.type)) {
      ElMessage.error('仅支持 JPG/JPEG/PNG/WEBP 格式')
      clearUploadFile()
      return
    }

    // 验证文件大小
    if (uploadFile.raw.size > 10 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过10MB')
      clearUploadFile()
      return
    }

    // 存储当前上传的文件（替换已存在的）
    currentUploadFile.value = uploadFile.raw as File

    // 读取图片并显示预览
    const reader = new FileReader()
    reader.onload = (e) => {
      collect.image = e.target?.result as string
    }
    reader.readAsDataURL(uploadFile.raw)

    // PNG格式解析元数据，使用当前用户配置的映射
    if (uploadFile.raw.type === 'image/png') {
      await parseImageMetadata(uploadFile.raw, userNodeFieldMap.value)
    }

    ElMessage.success('图片已准备好上传')
  } catch (error) {
    ElMessage.error(`处理图片失败: ${error instanceof Error ? error.message : '未知错误'}`)
    clearUploadFile()
  }
}

/**
 * 解析图片元数据
 * @param file 图片文件
 * @param map 可选的字段映射配置，默认为空对象
 */
const parseImageMetadata = async (file: File, map: NodeFieldMap = {}) => {
  try {
    // 调用ipc服务读取元数据，传入可选的map参数
    const result = await ipcService.readMetadata(file, map)
    if (result.success) {
      // 假设元数据结构包含prompt和rawPrompt
      collect.tags = result.metadata?.prompt || ''
      metadata.data = result.metadata?.rawPrompt || ''
      ElMessage.success('元数据解析成功')
    } else {
      ElMessage.error(`解析失败: ${result.error}`)
    }
  } catch (error) {
    console.error('解析元数据错误:', error)
    ElMessage.warning('提取图片信息失败')
  }
}

/**
 * 处理配置提交，重新解析元数据
 * @param map 新的字段映射配置
 */
const handleConfigSubmit = async (map: NodeFieldMap) => {
  // 保存新的映射配置
  userNodeFieldMap.value = map;
  
  // 如果有上传的文件，使用新配置重新解析
  if (currentUploadFile.value && currentUploadFile.value.type === 'image/png') {
    await parseImageMetadata(currentUploadFile.value, map)
  } else if (currentUploadFile.value) {
    ElMessage.info('只有PNG格式图片支持元数据解析')
  } else {
    ElMessage.info('配置已保存，请上传图片以应用新配置')
  }
}

// 重置表单
const resetForm = () => {
  collectForm.value?.resetFields();
  // 重置自定义字段
  collect.image = '';
  metadata.data = '';
  collect.rating = 0.0;
  collect.favorite = false;
  collect.disliked = false;
  // 清除上传文件
  clearUploadFile()
  // 重置映射配置
  userNodeFieldMap.value = {};
}

// 清除上传文件
const clearUploadFile = () => {
  currentUploadFile.value = null
  // 清空上传组件
  if (imageUpload.value) {
    imageUpload.value.clearFiles()
  }
  // 清除预览
  collect.image = ''
}

const loadCollects = () => {
  emit('loadCollects')
}
</script>

<style scoped lang="scss">
.add-container {
  border-radius: 12px;
  overflow: hidden;
  border: none;
  background: linear-gradient(135deg, var(--el-fill-color-lighter) 0%, var(--el-fill-color) 100%);

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.section-header {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);

  .icon {
    background: var(--el-color-primary);
    color: var(--el-color-white);
    width: 32px;
    height: 32px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
  }

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .action-button {
    margin-left: auto;
    margin-right: 8px;
  }
}

.form-section {
  padding-right: 20px;
  border-right: 1px solid var(--el-border-color-lighter);
}

.image-section {
  padding-left: 20px;
}

.custom-form {
  .el-form-item {
    margin-bottom: 22px;

    &:last-child {
      margin-bottom: 10px;
    }
  }

  .form-input {
    width: 100%;
    border-radius: 8px;

    :deep(.el-input__inner) {
      border-radius: 8px;
    }

    :deep(.el-textarea__inner) {
      border-radius: 8px;
    }
  }
}

.rating-favorite-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;

  .rating-item {
    display: flex;
    align-items: center;
  }
}

.custom-rate {
  :deep(.el-rate__item) {
    margin-right: 2px;
  }

  :deep(.el-rate__text) {
    margin-left: 8px;
    font-size: 14px;
    color: var(--el-color-primary);
  }
}

.image-preview-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preview-card {
  background-color: var(--el-bg-color);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: var(--el-box-shadow-light);
  border: 1px solid var(--el-border-color);
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;

  &.no-image {
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color);
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .image-placeholder {
    text-align: center;
    color: var(--el-text-color-secondary);

    .placeholder-icon {
      font-size: 60px;
      margin-bottom: 12px;
      color: var(--el-border-color);
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }
}

.image-uploader {
  :deep(.el-upload) {
    width: 100%;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
    padding: 20px;
    border-radius: 12px;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color);
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
    }
  }

  .upload-icon {
    font-size: 40px;
    color: var(--el-color-primary);
    margin-bottom: 12px;
  }

  .el-upload__text {
    font-size: 14px;
    color: var(--el-text-color-regular);

    .el-upload__tip {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
      margin-top: 8px;
      display: block;
    }
  }
}

.metadata-section {
  margin-top: 15px;

  .metadata-input {
    :deep(.el-textarea__inner) {
      border-radius: 8px;
      background-color: var(--el-fill-color-lighter);
      border: 1px solid var(--el-border-color);
    }
  }
}

.custom-viewer-toolbar {
  background: rgba(0, 0, 0, 0.7);
  border-radius: 20px;
  padding: 5px 10px;
  display: flex;
  gap: 8px;

  .el-button {
    background: rgba(255, 255, 255, 0.15);
    border: none;
    color: var(--el-color-white);
    transition: all 0.3s;

    &:hover {
      background: rgba(255, 255, 255, 0.3);
      transform: translateY(-2px);
    }
  }
}

@media (max-width: 768px) {
  .form-section {
    padding-right: 0;
    padding-bottom: 20px;
    border-right: none;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .image-section {
    padding-left: 0;
    padding-top: 20px;
  }

  .rating-favorite-container {
    flex-direction: column;
    gap: 12px;
  }

  .section-header {
    flex-wrap: wrap;

    .action-button {
      margin-left: 0;
      margin-top: 10px;
      width: 100%;
    }
  }
}
</style>
